package com.njy.provider.hystrix.service;


import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class HystrixService {

    @Value("${server.port}")
    private String port;

    public String paymentInfo_OK(Integer id) {
        return "线程池:  "+Thread.currentThread().getName()+", id:"+id+"\t"+"  paymentInfo_OK"+"  端口 "+port;
    }

    @HystrixCommand(fallbackMethod = "paymentInfoTimeOutFallbackMethod",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_TimeOut(Integer id) {
        try {
            TimeUnit.MILLISECONDS.sleep(4000);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:  "+Thread.currentThread().getName()+", id:"+id+"\t"+"  paymentInfo_TimeOut "+"  端口 "+port;
    }

    public String paymentInfoTimeOutFallbackMethod(Integer id){
        return "线程池:  "+Thread.currentThread().getName()+"进入fallback方法  "+port+"系统繁忙或者运行报错，请稍后再试,id:  "+id+"\t";
    }


    //================服务熔断========================


    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), // 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")
    })
    public String paymentCircuitBreaker(Integer id){
        if(id<0){
            throw  new RuntimeException("运行时异常-----参数为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t"+"调用成功，流水号: " + serialNumber;
    }


    public String paymentCircuitBreaker_fallback(Integer id){
        return "服务熔断";
    }

}
